<template>
    <div class="container-fluid p-4">
        <el-page-header @back="goBack" class="mb-4">
            <template #content>
                <div class="d-flex align-items-center">
                    <span class="fs-5 me-3">
                        考核试题管理：<strong>{{ currentExam?.title || '加载中...' }}</strong>
                    </span>
                    <el-tag type="success">
                        当前总分：{{ totalPoints }}
                    </el-tag>
                </div>
            </template>
            <template #extra>
                <div class="d-flex align-items-center">
                    <el-button type="primary" @click="openAddModal" :disabled="totalPoints >= 100">
                        <i class="bi bi-plus-circle me-2"></i>添加新试题
                    </el-button>
                </div>
            </template>
        </el-page-header>

        <el-card class="box-card" shadow="never">
            <template #header>
                <div class="card-header">
                    <h5>试题列表</h5>
                </div>
            </template>
            <div v-if="loading" class="text-center p-5">加载中...</div>
            <div v-else-if="questions.length === 0" class="text-center p-5 text-muted">
                暂无试题，请点击右上角按钮添加。
            </div>
            <div v-else>
                <div v-for="question in sortedQuestions" :key="question.examQuestion.id"
                    class="question-item mb-4 p-3 border rounded">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <p><strong>{{ question.examQuestion.sequence }}.【{{ getQuestionTypeName(question.examQuestion.questionType) }} |
                                    {{
                                        question.examQuestion.points }}分】</strong></p>
                            <p class="mb-2">{{ question.examQuestion.content }}</p>
                            <div v-if="question.options && question.options.length > 0">
                                <div v-for="option in question.options" :key="option.id" class="option ps-3 mb-1"
                                    :class="{ 'text-success fw-bold': option.isCorrect }">
                                    {{ getOptionLabel(option.sequence) }}. {{ option.optionContent }}
                                    <i v-if="option.isCorrect" class="bi bi-check-circle-fill text-success ms-2"></i>
                                </div>
                            </div>
                            <div v-else class="mt-2">
                                <p class="text-muted mb-0">参考答案：{{ question.examQuestion.referenceAnswer }}</p>
                            </div>
                        </div>
                        <div class="ms-4">
                            <el-button type="primary" link @click="openEditModal(question)">编辑</el-button>
                            <el-button type="danger" link
                                @click="handleDeleteQuestion(question.examQuestion.id)">删除</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </el-card>

        <QuestionEditModal v-if="modalVisible" v-model="modalVisible" :exam-id="currentExamId"
            :question-data="editingQuestion" :current-total-points="totalPoints" :existing-sequences="existingSequences" @success="onModalSuccess" />
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { storeToRefs } from 'pinia'; // 1. 导入 storeToRefs
import { useExamStore } from '@/stores/exam.js'; // 2. 导入你的 exam store
import QuestionEditModal from '@/components/alert/teacher/QuestionEditModal.vue';

// --- 路由和状态管理 ---
const route = useRoute();
const router = useRouter();
const examStore = useExamStore(); // 3. 实例化 store
const currentExamId = ref(route.params.examId);
// 4. 使用 storeToRefs 从 store 中获取响应式的数据
// 这样模板中就可以直接使用 questions, loading, currentExam
// 并且当 store 中的数据变化时，页面会自动更新
const { questions, loading, currentExam } = storeToRefs(examStore);

// --- 计算属性 ---
const totalPoints = computed(() => {
    if (!questions.value) return 0;
    return questions.value.reduce((sum, q) => sum + (q.examQuestion?.points || 0), 0);
});
const sortedQuestions = computed(() => {
  // 检查 questions.value 是否存在且为数组
  if (!Array.isArray(questions.value)) {
    return [];
  }
  // 创建一个数组的副本进行排序，以避免直接修改 store 中的状态
  return [...questions.value].sort((a, b) => {
    return a.examQuestion.sequence - b.examQuestion.sequence;
  });
});
const existingSequences = computed(() => {
    if (!questions.value) return [];
    return questions.value.map(q => q.examQuestion.sequence);
});
// --- 生命周期钩子 ---
onMounted(() => {
    // 页面加载时，调用 store 中的 action 来获取数据
    examStore.fetchQuestionsByExamId({
        examId: currentExamId.value,
        pageSize: -1 // 传入-1表示不分页，获取全部试题
    });
});

// --- 事件处理 ---
const goBack = () => {
    router.back();
};

const handleDeleteQuestion = (questionId) => {
    ElMessageBox.confirm('确定要删除这道试题吗？此操作不可恢复。', '警告', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // 调用 store 中的删除 action
        examStore.deleteQuestion(questionId, () => {
            ElMessage.success('删除成功！');
            onModalSuccess(); // 删除成功后刷新列表
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};


const onModalSuccess = () => {
    // 当弹窗操作成功后，重新调用接口刷新列表
    examStore.fetchQuestionsByExamId({
        examId: currentExamId.value,
        pageSize: -1
    });
};

// --- 弹窗相关 ---
const modalVisible = ref(false);
const editingQuestion = ref(null);

const openAddModal = () => {
    editingQuestion.value = null; // 清空编辑数据，表示是新增
    modalVisible.value = true;
};

const openEditModal = (question) => {
    editingQuestion.value = question; // 传入当前题目数据，表示是编辑
    modalVisible.value = true;
};

// --- 辅助函数 ---
const getQuestionTypeName = (type) => {
    const map = {
        single_choice: '单选题',
        multi_choice: '多选题',
        true_false: '判断题',
        fill_blank: '填空题',
        matching: '匹配题',
        short_answer: '简答题',
        essay: '论述题',
        case_analysis: '案例分析题',
        practical: '实操题',
        file_upload: '文件上传题'
    };
    return map[type] || '未知题型';
};

const getOptionLabel = (sequence) => {
    return String.fromCharCode(64 + sequence); // 1->A, 2->B
};
</script>

<style scoped>
.question-item {
    background-color: #f9fafb;
    transition: box-shadow 0.3s;
}

.question-item:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.option.is-correct {
    color: var(--el-color-success);
    font-weight: bold;
}
</style>